<template>
  <div class="app-container product-view">
    <div v-if="!open">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
        <el-row>
          <el-form-item label="所属商家" prop="merId">
            <el-select v-model="queryParams.merId" placeholder="请选择所属商家" filterable size="mini">
              <el-option v-for="mer in merListOptions"
                         :key="mer.id"
                         :label="mer.shopName"
                         :value="mer.id"/>
            </el-select>
          </el-form-item>

          <el-form-item label="商品分类" prop="cateId">
            <el-select v-model="queryParams.cateId" @change="confirm" filterable size="mini">
              <el-option v-for="item in productTypeChildOptions"
                         :key="item.id" :label="item.typeName"
                         :value="item.id">{{ item.typeName }}
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="商品名称" prop="storeName">
            <el-input v-model="queryParams.storeName" placeholder="请输入商品/服务名称" clearable size="mini"
                      @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-row>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <router-link :to="'/mer/list'" class="link-type">
            <el-button icon="el-icon-back" size="mini">
              返 回
            </el-button>
          </router-link>
        </el-col>
        <!--        <el-col :span="1.5">-->
        <!--          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"-->
        <!--                     v-hasPermi="['module:product:add']">新增</el-button>-->
        <!--        </el-col>-->
        <el-col :span="1.5">
          <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                     v-hasPermi="['module:product:edit']">修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                     v-hasPermi="['module:product:remove']">删除
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="ID" align="center" prop="id" width="60"/>
        <el-table-column label="商品名称" align="center" prop="storeName" width="150"/>
        <el-table-column label="活动截止日期" align="center" prop="activeEndTime" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.activeEndTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品图片" align="center" prop="imagePath">
          <template slot-scope="scope">
            <a :href="scope.row.imagePath" style="color: #42b983" target="_blank">
              <img :src="scope.row.imagePath" title="点击打开" style="width:80px;height:50px;">
            </a>
          </template>
        </el-table-column>
        <el-table-column label="二维码" align="center" width="150">
          <template slot-scope="scope">
            <el-popover placement="right" width="400" trigger="hover">
              <el-image style="width: 380px; height: 380px" :src="scope.row.qrCode" fit="fill"/>
              <i class="el-icon-picture" slot="reference"/>
            </el-popover>
            <el-button size="mini" type="text" icon="el-icon-download"
                       @click="downloadImg(scope.row)">{{ scope.row.productNo }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="商品分类" align="center" prop="cateChildName"/>
        <el-table-column label="商品价格" align="center" prop="price"/>
        <!--        <el-table-column label="库存" align="center" prop="stock" />-->
        <el-table-column label="内部链接地址" align="center" prop="sales" width="150">
          <template slot-scope="scope">
            <span>/pages/product/detail/index?id={{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="销量" align="center" prop="sales"/>
        <el-table-column label="热销" align="center" key="isHot">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isHot"
                       :active-value="1"
                       :inactive-value="0"
                       @change="handleIshotChange(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort"/>
        <el-table-column label="浏览量" align="center" prop="browse"/>

        <el-table-column label="状态" align="center" prop="isShow" fixed="right">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isShow === 0" style="cursor: pointer" :type="'info'">已下架</el-tag>
            <el-tag v-if="scope.row.isShow === 1" style="cursor: pointer" :type="''">已上架</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="resetQrCode(scope.row)"
                       v-hasPermi="['module:product:edit']">二维码生成
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['module:product:edit']">修改
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['module:product:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0"
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>

    </div>

    <div v-if="open">
      <!-- 添加或修改商品对话框 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="product-edit-view ">
        <el-scrollbar wrap-class="scrollbar-wrapper">
          <el-row>
            <el-col :span="12">
              <el-form-item :label="name+'名称'" prop="storeName">
                <el-input size="mini" v-model="form.storeName" placeholder="请输入 商品 / 服务 名称" ref="storeName"/>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item :label="name+'简介'" prop="storeInfo" style="width:50%;">
                <el-input type="textarea" size="mini" v-model="form.storeInfo" placeholder="请输入商品简介" rows="3"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="关键字" prop="keyword" style="width:100%;">
                <el-input v-model="form.keyword" size="mini" placeholder="请输入关键字"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="展示价格" prop="labelPrice" style="width:300px;">
                <el-input v-model="form.labelPrice" size="mini" placeholder="请输入展示价格"/>
              </el-form-item>
            </el-col>

          </el-row>

          <el-row>
            <el-form-item :label="name+'图片'">
              <single-pic v-model="form.imagePath" type="image" @handleChecked="chooseGoodsImg"
                          :uploadType="1" :num="1" :width="150" :height="150"/>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="轮播图">
              <imageUpload :uploadType="1" v-model="form.sliderImagePath" @handleUploadSuccess="chooseLunboImg"
                           @handleRemove="removeImg"/>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="是否支持预约" prop="isAppointment">
                <el-radio-group v-model="form.isAppointment" size="mini">
                  <el-radio :value="1" :label="1">预约型</el-radio>
                  <el-radio :value="0" :label="0">正常购买型</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="14">
              <el-form-item label="是否上门服务" prop="isVisit">
                <el-radio-group v-model="form.isVisit" size="mini">
                  <el-radio :value="1" :label="1">上门服务</el-radio>
                  <el-radio :value="0" :label="0">到店服务</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="是否需要绑定手机号" prop="isNeedPhone">
                <el-radio-group v-model="form.isNeedPhone" size="mini">
                  <el-radio :value="0" :label="0">不需要即可购买</el-radio>
                  <el-radio :value="1" :label="1">需要手机号才能购买</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="14">
              <el-form-item label="是否需要绑定小区" prop="isNeedEstate">
                <el-radio-group v-model="form.isNeedEstate" size="mini">
                  <el-radio :value="0" :label="0">不需要即可购买</el-radio>
                  <el-radio :value="1" :label="1">需要绑定小区才能购买</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <!--            <el-col :span="24">-->
            <!--              <el-col :span="7">-->
            <!--                <el-form-item label="是否有活动期限" prop="isActive">-->
            <!--                  <el-radio-group v-model="form.isActive" size="mini">-->
            <!--                    <el-radio :value="0" :label="0">不限制期限</el-radio>-->
            <!--                    <el-radio :value="1" :label="1">有期限</el-radio>-->
            <!--                  </el-radio-group>-->
            <!--                </el-form-item>-->
            <!--              </el-col>-->
            <!--              <el-col :span="12" v-if="form.isActive == 1">-->
            <!--                <el-form-item label="查询时间" prop="activeDateRange">-->
            <!--                  <el-date-picker v-model="form.activeDateRange" size="mini" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"-->
            <!--                                  range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>-->
            <!--                </el-form-item>-->
            <!--              </el-col>-->
            <!--            </el-col>-->

            <el-col :span="24">
              <el-col :span="6">
                <el-form-item label="是否限购" prop="isLimit">
                  <el-radio-group v-model="form.isLimit" size="mini">
                    <el-radio :value="0" :label="0">不限购</el-radio>
                    <el-radio :value="1" :label="1">限购</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col :span="6" v-if="form.isLimit === 1">
                <el-form-item label="限购数量" prop="limitCount">
                  <el-input v-model="form.limitCount" type="number" size="mini" placeholder="请输入限购数量"/>
                </el-form-item>
              </el-col>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="24">
              <el-col :span="24">
                <el-form-item label="商品规格" prop="specType">
                  <el-radio-group v-model="form.specType" @change="changeSpec" size="mini">
                    <el-radio :value="0" :label="0">单规格</el-radio>
                    <el-radio :value="1" :label="1">多规格</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <!--              <el-col :span="9">-->
              <!--                <el-form-item label="商品分类类型" prop="isLife">-->
              <!--                  <el-radio-group v-model="form.isLife" @change="changeIsLife" size="mini">-->
              <!--                    <el-radio :value="0" :label="0">非生活服务类</el-radio>-->
              <!--                    <el-radio :value="1" :label="1">生活服务类</el-radio>-->
              <!--                  </el-radio-group>-->
              <!--                </el-form-item>-->
              <!--              </el-col>-->

              <el-col :span="24">
                <el-form-item label="商品分类" prop="cateId" style="width: 35%;">
                  <el-select v-model="form.cateId" style="width: 100%;" @change="confirm" size="mini">
                    <el-option v-for="item in productTypeChildOptions"
                               :key="item.id" :label="item.typeName"
                               :value="item.id">{{ item.typeName }}
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <!-- 多规格添加-->
              <el-col :span="24" v-if="form.specType === 1" class="noForm">
                <el-col :span="24">
                  <el-form-item label="选择规格：" prop="ruleId" style="width: 35%;">
                    <div class="acea-row row-middle">
                      <el-select v-model="form.ruleId" style="width: 100%;" @change="confirm" size="mini">
                        <el-option v-for="rule in ruleListOptions"
                                   :key="rule.id" :label="rule.ruleName"
                                   :value="rule.id"/>
                      </el-select>
                    </div>
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <el-form-item v-if="attrs.length!==0">
                    <div v-for="(item, index) in attrs" :key="index">
                      <div class="acea-row row-middle"><span class="mr5">{{ item.value }}</span>
                        <i class="el-icon-circle-close" @click="handleRemoveRole(index)"></i>
                      </div>
                      <div class="rulesBox">
                        <el-tag type="dot" closable color="primary" class="mr20"
                                v-for="(j, indexn) in item.detail"
                                :key="indexn" :name="j"
                                @close="handleRemove2(item.detail,indexn)">{{ j }}
                        </el-tag>
                        <el-input placeholder="请输入属性名称" v-model="item.detail.attrsVal" style="width: 200px"
                                  size="mini">
                          <el-button slot="append" size="mini" type="primary"
                                     @click="createAttr(item.detail.attrsVal,index)">添加
                          </el-button>
                        </el-input>
                      </div>
                    </div>
                  </el-form-item>
                </el-col>

                <el-col :span="24" v-if="createBtn">
                  <el-form-item>
                    <el-button type="primary" icon="md-add" @click="addBtn" class="mr15" size="mini">添加新规格
                    </el-button>
                    <el-button type="success" @click="generate(0)" size="mini">立即生成</el-button>
                    <el-button type="warning" @click="generate(1)" size="mini">重新生成</el-button>
                  </el-form-item>
                </el-col>

                <el-col :span="24" v-if="showIput">
                  <el-col :xl="6" :lg="9" :md="10" :sm="24" :xs="24">
                    <el-form-item label="规格：">
                      <el-input placeholder="请输入规格" v-model="formDynamic.attrsName" size="mini"/>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="6" :lg="9" :md="10" :sm="24" :xs="24">
                    <el-form-item label="规格值：">
                      <el-input v-model="formDynamic.attrsVal" placeholder="请输入规格值" size="mini"/>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="6" :lg="5" :md="10" :sm="24" :xs="24">
                    <el-button type="primary" @click="createAttrName" size="mini">确定</el-button>
                    <el-button type="danger" @click="offAttrName" size="mini">取消</el-button>
                  </el-col>
                </el-col>
                <!-- 多规格设置-->
                <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24" v-if="manyFormValidate!==undefined
                          && manyFormValidate.length && form.header.length!==0 && attrs.length!==0">
                  <!-- 多规格表格-->
                  <el-col :span="24">
                    <el-form-item label="商品属性：" class="labeltop">
                      <el-table :data="manyFormValidate" size="mini" style="width: 50%;">
                        <el-table-column type="myindex" v-for="(item,index) in form.header" :key="index"
                                         :label="item.title" :property="item.slot" align="center">
                          <template slot-scope="scope">
                            <div v-if="scope.column.property.indexOf('value') !== -1" align="center">
                              {{ scope.row[scope.column.property] }}
                            </div>
                            <div v-else-if="scope.column.property === 'action'" align="center">
                              <a @click="delAttrTable(scope.$index)" align="center">删除</a>
                            </div>
                            <div v-else align="center">
                              <el-input v-model="scope.row[scope.column.property]" align="center" size="mini"/>
                            </div>
                          </template>
                        </el-table-column>

                      </el-table>
                    </el-form-item>
                  </el-col>
                </el-col>
              </el-col>

              <!-- 单规格表格-->
              <el-col :xl="23" :lg="24" :md="24" :sm="24" :xs="24" v-if="form.specType === 0">
                <el-form-item>
                  <el-table :data="oneFormValidate" size="mini" style="width: 50%;">
                    <el-table-column prop="price" label="售价" align="center">
                      <template slot-scope="scope">
                        <el-input type="text" v-model="scope.row.price" size="mini"/>
                      </template>
                    </el-table-column>
                    <el-table-column prop="otPrice" label="原价" align="center">
                      <template slot-scope="scope">
                        <el-input type="text" v-model="scope.row.otPrice" size="mini"/>
                      </template>
                    </el-table-column>
                    <el-table-column prop="stock" label="库存" align="center">
                      <template slot-scope="scope">
                        <el-input type="text" v-model="scope.row.stock" size="mini"/>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </el-col>
            </el-col>

            <el-col :span="24">
              <el-form-item label="排序" prop="sort" style="width: 35%;">
                <el-input v-model="form.sort" type="number" placeholder="请输入排序" size="mini"/>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="当前销量" prop="sales" style="width: 35%;">
                <el-input v-model="form.sales" type="number" placeholder="请输入当前销量" size="mini"/>
              </el-form-item>
            </el-col>

            <!--            <el-col :span="24">-->
            <!--              <el-form-item label="状态" prop="isShow">-->
            <!--                <el-radio-group v-model="form.isShow" size="mini">-->
            <!--                  <el-radio v-for="dict in productStateOption"-->
            <!--                            :label="parseInt(dict.dictValue)">{{dict.dictLabel}}</el-radio>-->
            <!--                </el-radio-group>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->

            <el-col :span="18">
              <el-form-item label="购买须知" prop="buyingTips">
                <editor v-model="form.buyingTips" :min-height="192" size="mini"/>
              </el-form-item>
            </el-col>

            <el-col :span="18">
              <el-form-item label="产品描述" prop="description">
                <editor v-model="form.description" :min-height="192" size="mini"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-scrollbar>
      </el-form>

      <div slot="footer" class="dialog-footer" style="margin-top: 10px">
        <el-button :loading="buttonLoading" size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </div>
  </div>

</template>

<script>
import {
  listProduct,
  getProduct,
  delProduct,
  addProduct,
  updateProduct,
  isFormatAttr,
  goAddData,
  resetQrCode,
  listProductByMerId,
  handleIshotChange
} from "@/api/module/product/list";
import {listNoPage as listNoPageMer} from "@/api/module/mer/mer";
import {listType,} from "@/api/module/product/type";

import {listNoPage} from "@/api/module/product/rule";
import {treeSelect} from "@/api/module/product/type";

import singlePic from '@/components/SingleMaterial'
import editor from '@/components/Editor';
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import Template from "../wx/template";

export default {
  name: "Product",
  components: {Template, editor, Treeselect, singlePic},
  data() {
    return {
      name: '商品',
      activeName: '0',
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      merListOptions: [],
      // 商品表格数据
      productList: [],
      merProductList: [],
      // 弹出层标题
      title: "",
      isShowLimit: false,
      // 是否显示弹出层
      open: false,
      activeDateRange: [],
      productStateOption: [],
      yesOrNoOption: [],
      //总类
      productTypeOptions: [],
      //子分类
      productTypeChildOptions: [],
      createBtn: false,
      showIput: false,
      // 规格数据
      formDynamic: {
        attrsName: '',
        attrsVal: ''
      },
      // 批量设置表格data
      oneFormBatch: [{
        price: 0,
        otPrice: 0,
        stock: 9999,
      }],
      emptyUrl: '',
      attrs: [],
      ruleListOptions: [],
      shopListOptions: [],
      formDynamicNameData: [],
      isBtn: false,
      manyFormValidate: [],
      subTypeLabel: '分成金额',
      subTypeUnit: '元',
      // 单规格表格data
      oneFormValidate: [
        {
          price: 0,
          otPrice: 0,
          stock: 9999,
        }
      ],
      images: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cateId: null,
        storeName: '',
        keyword: '',
        isCoupon: 0,
        isActive: 0,
        isLife: undefined,
        orderSort: 1,
        isPlatform: 0,
      },
      // 查询参数
      queryParamsPty: {
        pageNum: 1,
        pageSize: 100,
        parentId: 0,
        isPlatform: 0
      },
      splits: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cateId: [
          {required: true, message: "请选择商品分类", trigger: "blur"}
        ],
        merId: [
          {required: true, message: "请选择所属商家", trigger: "blur"}
        ],
        image: [
          {required: true, message: "商品图片不能为空", trigger: "blur"}
        ],
        sliderImage: [
          {required: true, message: "轮播图不能为空", trigger: "blur"}
        ],
        storeName: [
          {required: true, message: "商品名称不能为空", trigger: "blur"}
        ],
        storeInfo: [
          {required: true, message: "商品简介不能为空", trigger: "blur"}
        ],
        keyword: [
          {required: true, message: "关键字不能为空", trigger: "blur"}
        ],
        price: [
          {required: true, message: "商品价格不能为空", trigger: "blur"}
        ],
        isLimit: [
          {required: true, message: "请选择是否限购", trigger: "blur"}
        ],
        isVisit: [
          {required: true, message: "请选择是否上门", trigger: "blur"}
        ],
        isAppointment: [
          {required: true, message: "请选择是否支持预约", trigger: "blur"}
        ],
        isLife: [
          {required: true, message: "请选择商品分类类型", trigger: "blur"}
        ],
        isNeedPhone: [
          {required: true, message: "请选择是否需要绑定手机号后购买", trigger: "blur"}
        ],
        isNeedEstate: [
          {required: true, message: "请选择是否需要绑定小区后购买", trigger: "blur"}
        ],
      },
      checkAll: false,
      isIndeterminate: true,
    };
  },
  created() {
    this.getRuleList(0);
    this.getList();
    // this.getTreeSelect();
    this.getMerListByMyUserId();
    this.getProductTypeChildList();
    this.getDicts("yes_or_no").then(response => {
      this.yesOrNoOption = response.data;
    });

    this.getDicts("product_state").then(response => {
      this.productStateOption = response.data;
    });
  },
  methods: {
    getMerListByMyUserId() {
      listNoPageMer({isShowProduct: 0}).then(response => {
        this.merListOptions = response.data;
      });
    },
    resetQrCode(row) {
      var data = {
        id: row.id
      };
      resetQrCode(data).then(response => {
        if (response.code === 200) {
          this.msgSuccess("生成成功");
          this.getList();
        } else {
          this.msgError("生成失败");
        }
      });
    },
    downloadImg(row) {
      window.location.href = process.env.VUE_APP_BASE_API + "/common/download/product/" + row.id;
    },
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    goAddData() {
      goAddData().then(response => {
        console.log('response.data.estates', response.data.estates);
        this.form.estates = response.data.estates;
        this.splits = response.data.splits;
      });
    },
    changeIsLife(val) {
      this.queryParamsPty.isPlatform = val;
      this.getProductTypeChildList()
    },
    getProductTypeChildList() {
      listType(this.queryParamsPty).then(response => {
        this.productTypeChildOptions = response.rows;
      });
    },
    getRuleList(ruleId) {
      listNoPage(ruleId).then(res => {
        this.ruleListOptions = res.data;
      })
    },
    getShopListOptions() {
      listNoPageMer().then(res => {
        this.shopListOptions = res.data;
      })
    },
    getTreeSelect() {
      treeSelect().then(res => {
        this.productTypeOptions = res.data;
        console.log('productTypeOptions', res.data)
      })
    },
    chooseGoodsImg(data) {
      console.log("product chooseGoodsImg", data);
      if (data.length > 0) {
        this.form.imagePath = data[0].imgUrl;
        this.form.image = data[0].url;
      }
    },
    chooseLunboImg(data) {
      console.log("product chooseLunboImg", data);
      this.form.sliderImage = "";
      this.form.sliderImagePath = "";
      var imgUrlArray = data.imgUrl;
      // var imgUrlArrayPath = data.imgUrl;
      for (var index in imgUrlArray) {
        var fileName = imgUrlArray[index].name.replace("https://www.caihengyun.com/chyimg/", "");
        this.form.sliderImage += fileName + ",";
        this.form.sliderImagePath += imgUrlArray[index].url + ",";
      }
      this.form.sliderImage = this.form.sliderImage.substring(0, this.form.sliderImage.length - 1);
      this.form.sliderImagePath = this.form.sliderImagePath.substring(0, this.form.sliderImagePath.length - 1);
      // console.log('sliderImageArray',this.form.sliderImageArray)
    },
    removeImg(data) {
      console.log('removeImg', data);
      this.form.sliderImage = data.imgUrl;
    },
    // 改变规格
    changeSpec(val) {
      console.log('changeSpec', val)
      // specType
    },
    confirm(val) {
      console.log('confirm', val);
      // console.log('confirm',this.ruleListOptions[val]);
      // console.log('this.ruleListOptions[val].ruleValueArray',this.ruleListOptions[val].ruleValueArray);
      var that = this;
      for (var index in that.ruleListOptions) {
        console.log('that.ruleListOptions[index]', that.ruleListOptions[index]);
        if (that.ruleListOptions[index].id === val) {
          that.attrs = that.ruleListOptions[index].ruleValueArray;
          that.form.ruleId = that.ruleListOptions[index].id;
          that.createBtn = true;
        }
      }
      console.log('that.form.ruleId', that.form.ruleId);
      this.getRuleList(val);
    },
    // 立即生成
    generate(isReset) {
      console.log('generate  this.attrs', this.attrs);
      if (this.form.id === undefined) {
        this.form.id = 0;
      }
      isFormatAttr(this.form.id, {attrs: this.attrs}, isReset).then(res => {
        console.log('generate  isFormatAttr', res);
        this.manyFormValidate = res.data.value;
        let headerdel = {
          title: '操作',
          slot: 'action',
          fixed: 'right',
          width: 220
        };
        res.data.header.push(headerdel);
        console.log(' generate  res.data.header', res.data.header);
        this.form.header = res.data.header;
        console.log('generate  this.form.header', this.form.header);
        let header = res.data.header;
        console.log(' generate  header', header);
        header.pop();
        console.log(' generate  manyFormValidate', this.manyFormValidate);
      }).catch(res => {
      })
    },
    // 添加按钮
    addBtn() {
      this.clearAttr();
      this.createBtn = false;
      this.showIput = true;
    },
    // 取消
    offAttrName() {
      this.showIput = false;
      this.createBtn = true;
    },
    clearAttr() {
      this.formDynamic.attrsName = '';
      this.formDynamic.attrsVal = '';
    },
    // 删除规格
    handleRemoveRole(index) {
      this.attrs.splice(index, 1);
      this.manyFormValidate.splice(index, 1);
    },
    // 删除属性
    handleRemove2(item, index) {
      item.splice(index, 1);
    },
    // 添加规则名称
    createAttrName() {
      if (this.formDynamic.attrsName && this.formDynamic.attrsVal) {
        let data = {
          value: this.formDynamic.attrsName,
          detail: [
            this.formDynamic.attrsVal
          ]
        };
        console.log('data', data);
        this.attrs.push(data);
        var hash = {};
        console.log('this.attrs', this.attrs);
        this.attrs = this.attrs.reduce(function (item, next) {
          hash[next.value] ? '' : hash[next.value] = true && item.push(next);
          return item
        }, []);
        this.clearAttr();
        this.showIput = false;
        this.createBtn = true;
      } else {
        this.$message.warning('请添加完整的规格！');
      }
    },
    // 添加属性
    createAttr(num, idx) {
      if (num) {
        this.attrs[idx].detail.push(num);
        var hash = {};
        console.log('this.attrs[idx].detail', this.attrs[idx].detail);
        this.attrs[idx].detail = this.attrs[idx].detail.reduce(function (item, next) {
          hash[next] ? '' : hash[next] = true && item.push(next);
          return item
        }, [])
      } else {
        this.$message.warning('请添加属性！');
      }
    },
    // 用户状态修改
    handleIshotChange(row) {
      let text = row.isHot === "0" ? "关闭" : "开启";
      this.$confirm('确认要"' + text + '"为热销吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return handleIshotChange(row.id, row.isHot);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function () {
        row.isHot = row.isHot === "0" ? "1" : "0";
      });
    },
    // 删除表格中的属性
    delAttrTable(index) {
      this.manyFormValidate.splice(index, 1);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        merId: this.queryParams.merId,
        image: undefined,
        imagePath: undefined,
        sliderImage: undefined,
        sliderImageArray: [],
        sliderImagePath: undefined,
        storeName: undefined,
        storeInfo: undefined,
        keyword: undefined,
        barCode: undefined,
        cateId: this.queryParams.cateId,
        // cateChildId:undefined,
        ruleId: undefined,
        price: undefined,
        vipPrice: undefined,
        otPrice: undefined,
        postage: undefined,
        unitName: undefined,
        isLife: 0,
        sort: 1,
        sales: 0,
        stock: 0,
        isSale: 1,
        isPlatform: 0,
        isLimit: undefined,
        limitCount: undefined,
        isShow: undefined,
        isHot: undefined,
        isBenefit: undefined,
        isUseIntegral: undefined,
        isBest: undefined,
        isNew: undefined,
        description: '',
        createTime: undefined,
        updateTime: undefined,
        isPostage: undefined,
        isDel: undefined,
        merUse: undefined,
        giveIntegral: undefined,
        cost: undefined,
        isGood: undefined,
        ficti: undefined,
        browse: undefined,
        isCoupon: 0,
        isSub: 1,
        subType: 1,
        tempId: undefined,
        specType: 0,
        splitMoney: undefined,
        splitTypeId: undefined,
        isAppointment: undefined,
        isVisit: undefined,
        buyingTips: undefined,
        isActive: 0,
        activeBeginTime: undefined,
        activeEndTime: undefined,
        isNeedPhone: 0,
        isNeedEstate: 0,
        header: [],
        estates: [],
        estateIds: [],
        activeDateRange: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
      this.attrs = [];
      this.form.header = [];
      this.manyFormValidate = [];
      this.oneFormValidate = [
        {
          price: 0,
          otPrice: 0,
          stock: 9999,
        }
      ];
      this.goAddData();
      this.$nextTick((x) => { //正确写法
        this.$refs.storeName.focus();
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      var that = this;
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;

      getProduct(id).then(response => {
        console.log('getProduct', response.data);
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改商品";
        console.log(' that.form.rule', that.form.rule);
        if (that.form.rule !== null && that.form.rule !== undefined) {
          console.log(' that.form.rule 111', that.form.rule);
          that.attrs = that.form.rule.ruleValueArray;
        }
        that.splits = response.data.splits;
        that.form.header = [];
        console.log('that.form.specType', that.form.specType);
        if (that.form.specType === 0) {//单规格
          that.manyFormValidate = [];
          console.log('response.data.productValue["默认"]', response.data.productValue["默认"]);
          that.oneFormValidate[0] = response.data.productValue["默认"];
          console.log('oneFormValidate', that.oneFormValidate)
        } else {
          //多规格
          that.createBtn = true;
          console.log('that.manyFormValidate', that.manyFormValidate);
          that.generate(0);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // this.buttonLoading = true;
          if (this.form.image === undefined) {
            return this.$message.warning('请上传商品图片！');
          }
          if (this.form.sliderImage === undefined) {
            return this.$message.warning('请上传轮播图！');
          }

          if (this.form.specType === 0) {
            this.form.attrs = this.oneFormValidate;
            this.form.header = [];
            this.form.items = [];
          } else {
            this.form.items = this.attrs;
            this.form.attrs = this.manyFormValidate;
          }
          if (this.form.specType === 1 && this.manyFormValidate.length === 0) {
            return this.$message.warning('请点击生成规格！');
          }

          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addProduct(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除商品编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        return delProduct(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
  }
};
</script>

<style lang="scss" scoped>
.product-view {
  width: 100%;
  position: relative;
  overflow: hidden;

  .product-edit-view {
    box-shadow: 2px 2px 6px rgb(0 21 41 / 35%);
    padding: 20px;
  }

  .product-edit-view .el-scrollbar {
    height: calc(100vh - 12.5rem);
  }

  .scrollbar-wrapper {
    overflow-x: hidden !important;
  }
}
</style>
